package com.app.myApp.control;

import com.app.myApp.dao.UserDAO;
import com.app.myApp.dao.UserInfoDAO;
import com.app.myApp.dataobject.UserDO;
import com.app.myApp.dataobject.UserInfoDO;
import com.app.myApp.model.EmailReq;
import com.app.myApp.model.Response;
import com.app.myApp.model.User;
import com.app.myApp.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private UserInfoDAO userInfoDAO;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired  // 注入密码加密器
    private PasswordEncoder passwordEncoder;

    @Autowired  // 注入Redis模板
    private StringRedisTemplate redisTemplate;

    @Autowired
    private JwtUtils jwtUtils;

    // 生成6位数字验证码
    private String generateCode() {
        Random random = new Random();
        int code = random.nextInt(900000) + 100000;
        return String.valueOf(code);
    }

    // 发送验证码邮件（存储到Redis，设置5分钟过期）
    private boolean sendCode(String to) {
        String code = generateCode();
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            String from = "3186965058@qq.com";
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("验证码");
            message.setText("你的验证码是：" + code + "，5分钟内有效，请勿泄露给他人。");
            mailSender.send(message);

            // 存储验证码到Redis，键为"verify:email:用户邮箱"，过期时间5分钟
            redisTemplate.opsForValue().set(
                    "verify:email:" + to,
                    code,
                    5,
                    TimeUnit.MINUTES
            );
            return true;
        } catch (MailException e) {
            e.printStackTrace();  // 建议用日志框架记录
            return false;
        }
    }

    // 发送验证码接口
    @PostMapping("/users/sendEmailCode")
    public ResponseEntity<Response> sendEmailCode( @RequestBody EmailReq emailReq) {
        String email = emailReq.getEmailTo();
        // 简单校验邮箱格式
        if (!StringUtils.hasText(email) || !email.contains("@")) {
            return new ResponseEntity<>(Response.error("邮箱格式错误"), HttpStatus.BAD_REQUEST);
        }

        boolean sendSuccess = sendCode(email);
        if (sendSuccess) {
            return new ResponseEntity<>(Response.success("验证码已发送，请注意查收"), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(Response.error("验证码发送失败，请重试"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 注册接口
    @PostMapping("/users/register")
    public ResponseEntity<Response> userRegister( @RequestBody User user) {
        String email = user.getEmail();
        String password = user.getPassword();
        String code = user.getVerificationCode();
        String username = user.getUserName();

        // 1. 校验参数
        if (!StringUtils.hasText(email) || !StringUtils.hasText(password) || !StringUtils.hasText(code)) {
            return new ResponseEntity<>(Response.error("参数不能为空"), HttpStatus.BAD_REQUEST);
        }

        // 2. 校验验证码（从Redis获取）
        String storedCode = redisTemplate.opsForValue().get("verify:email:" + email);
        if (storedCode == null || !storedCode.equals(code)) {
            return new ResponseEntity<>(Response.error("验证码错误或已过期"), HttpStatus.BAD_REQUEST);
        }

        // 3. 校验用户是否已存在
        if (userDAO.findUserByEmail(email) != null) {
            return new ResponseEntity<>(Response.error("用户已存在，请直接登录"), HttpStatus.CONFLICT);
        }

        // 4. 加密密码
        String encodedPassword = passwordEncoder.encode(password);

        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setEmail(email);
        userInfoDO.setUserName(username);
        userInfoDO.setAvatarUrl("https://love-think-1355440206.cos.ap-shanghai.myqcloud.com/avatars/768a9281-6b6c-4efb-a73e-72845206a16a.png");
        int userInfoRows = userInfoDAO.insert(userInfoDO);
        // 5. 插入数据库
        int rows = userDAO.insertUser(email, encodedPassword);  //存入加密后的密码
        if (rows > 0 && userInfoRows>0) {
            redisTemplate.delete("verify:email:" + email);
            return new ResponseEntity<>(Response.success("注册成功"), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(Response.error("注册失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 登录接口
    @PostMapping("/users/login")
    public ResponseEntity<Response> userLogin(@RequestBody User user) {
        String email = user.getEmail();
        String password = user.getPassword();

        // 1. 校验参数
        if (!StringUtils.hasText(email) || !StringUtils.hasText(password)) {
            return new ResponseEntity<>(Response.error("邮箱或密码不能为空"), HttpStatus.BAD_REQUEST);
        }

        // 2. 查询用户是否存在
        UserDO dbUser = userDAO.findUserByEmail(email);
        UserInfoDO userInfo = userInfoDAO.selectByEmail(email);
        if (dbUser == null) {
            return new ResponseEntity<>(Response.error("用户不存在，请先注册"), HttpStatus.NOT_FOUND);
        }

        // 3. 验证密码
        if (passwordEncoder.matches(password, dbUser.getPassword())) {
            // 3.1 生成 Token（用用户 email 作为唯一标识）
            String token = jwtUtils.generateToken(email);

            // 3.2 构建返回数据（屏蔽敏感字段 password）
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token); // 返回 Token
            responseData.put("email", dbUser.getEmail()); // 返回用户邮箱
            responseData.put("userName", userInfo.getUserName()); // 返回用户名

            // 3.3 返回 Token + 用户信息
            return new ResponseEntity<>(Response.success(responseData), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(Response.error("密码错误"), HttpStatus.BAD_REQUEST);
        }
    }


}
